﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Admin_question : System.Web.UI.Page
{
    myDataSetTableAdapters.QuestionsTableAdapter quesAdapter = new myDataSetTableAdapters.QuestionsTableAdapter();
    myDataSetTableAdapters.QuestionTypeTableAdapter quesTypeAdapter = new myDataSetTableAdapters.QuestionTypeTableAdapter();
    myDataSetTableAdapters.AnswersTableAdapter answerAdapter = new myDataSetTableAdapters.AnswersTableAdapter();
    myDataSetTableAdapters.Survey_QuestionTableAdapter surQuesAdapter = new myDataSetTableAdapters.Survey_QuestionTableAdapter();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Panel1.Visible = false;
            Panel3.Visible = false;
            Panel4.Visible = false;
            display();
            myDataSet.QuestionTypeDataTable quesTypeTable = quesTypeAdapter.GetData();
            DropDownList1.AppendDataBoundItems = true;
            DropDownList1.DataSource = quesTypeTable.DefaultView;
            DropDownList1.DataTextField = "type";
            DropDownList1.DataValueField = "id";
            DropDownList1.DataBind();
        }
    }

    protected void display()
    {
        myDataSet.QuestionsDataTable quesTable = quesAdapter.GetDataConvert();
        GridView1.DataSource = quesTable;
        GridView1.DataBind();
    }

    protected void displayAnswer(int id)
    {
        myDataSet.AnswersDataTable answerTable = answerAdapter.GetDataByQuesId(id);
        GridView2.DataSource = answerTable;
        GridView2.DataBind();
    }

    protected void clear()
    {
        txtId.Text = "";
        txtQues.Text = "";
        DropDownList1.SelectedValue = "-1";
        lblResult.Text = null;
        lblQuesError.Visible = false;
        lblQuesTypeError.Visible = false;
    }

    protected void clearAnswer()
    {
        txtAnswerId.Text = "";
        txtAnswer.Text = "";
        lblAnswerError.Visible = false;
    }

    protected bool checkEmpty()
    {
        bool status = true;
        if (txtQues.Text.Trim() == "")
        {
            lblQuesError.Visible = true;
            status = false;
        }
        else
        {
            lblQuesError.Visible = false;
        }
        if (DropDownList1.SelectedValue == "-1")
        {
            lblQuesTypeError.Visible = true;
            status = false;
        }
        else
        {
            lblQuesTypeError.Visible = false;
        }
        return status;
    }

    protected bool checkAnswerEmpty()
    {
        bool status = true;
        if (txtAnswer.Text.Trim() == "")
        {
            lblAnswerError.Visible = true;
            status = false;
        }
        else
        {
            lblAnswerError.Visible = false;
        }
        return status;
    }

    protected void cmdSearchEnable_Click(object sender, EventArgs e)
    {
        display();
        txtId.Enabled = true;
        txtId.BackColor = System.Drawing.Color.White;
        cmdSearch.Text = "Search";
        cmdClear.Visible = true;
        clear();
        if (cmdSearchEnable.Text == "Enable Search Area")
        {
            Panel1.Visible = true;
            cmdSearchEnable.Text = "Disable Search Area";
            cmdAddEnable.Text = "Enable Add Area";
        }
        else
        {
            Panel1.Visible = false;
            cmdSearchEnable.Text = "Enable Search Area";
        }
    }

    protected void cmdAddEnable_Click(object sender, EventArgs e)
    {
        display();
        txtId.Enabled = false;
        txtId.BackColor = System.Drawing.Color.WhiteSmoke;
        cmdSearch.Text = "Add new";
        cmdClear.Visible = true;
        clear();
        if (cmdAddEnable.Text == "Enable Add Area")
        {
            Panel1.Visible = true;
            cmdAddEnable.Text = "Disable Add Area";
            cmdSearchEnable.Text = "Enable Search Area";
        }
        else
        {
            Panel1.Visible = false;
            cmdAddEnable.Text = "Enable Add Area";
        }
    }

    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        if (cmdSearch.Text == "Search")
        {
            try
            {
                Panel1.Visible = true;
                string strSQL = "SELECT id, question, question_type_id from Questions where";
                strSQL += " question like N'%" + txtQues.Text.Trim() + "%'";
                if (DropDownList1.SelectedValue != "-1")
                {
                    strSQL += " and question_type_id = " + DropDownList1.SelectedValue.ToString();
                }
                if (txtId.Text.Trim() != "")
                {
                    strSQL += " and id = " + txtId.Text.Trim();
                }
                string strConnection = ConfigurationManager.ConnectionStrings["EnvironmentSurveyConnectionString"].ConnectionString;
                SqlConnection conn = new SqlConnection(strConnection);
                SqlCommand sqlCmd = new SqlCommand(strSQL, conn);
                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                GridView1.DataSource = dt;
                GridView1.DataBind();
                if (dt.Rows.Count != 0)
                {
                    if (dt.Rows.Count == 1)
                    {
                        lblResult.Text = "There is 1 result";
                    }
                    else
                    {
                        lblResult.Text = "There are " + dt.Rows.Count + " results";
                    }
                }
                else
                {
                    lblResult.Text = "0 result... Please search again!";
                }
            }
            catch
            {
                RegisterStartupScript("as", "<script>alert('Input wrong format!')</script>");
            }
        }
        else if (cmdSearch.Text == "Add new")
        {
            if (checkEmpty())
            {
                quesAdapter.InsertQuery(txtQues.Text.Trim(), int.Parse(DropDownList1.SelectedValue.ToString()));
                display();
                PanelButton.Visible = false;
                Panel1.Visible = false;
                Panel2.Visible = false;
                Panel3.Visible = true;
                Panel4.Visible = true;
                string strSQL = "SELECT top 1 id, question from Questions order by id desc";
                string strConnection = ConfigurationManager.ConnectionStrings["EnvironmentSurveyConnectionString"].ConnectionString;
                SqlConnection conn = new SqlConnection(strConnection);
                SqlCommand sqlCmd = new SqlCommand(strSQL, conn);
                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                txtQuestionIdAnswer.Text = dt.Rows[0]["id"].ToString();
                lblQuestionAnswer.Text = dt.Rows[0]["question"].ToString();
                displayAnswer(int.Parse(txtQuestionIdAnswer.Text.Trim()));
                txtAnswerId.Enabled = false;
                txtAnswerId.BackColor = System.Drawing.Color.WhiteSmoke;
                cmdAddAnswer.Text = "Add";
                clearAnswer();
            }
        }
        else
        {
            int questionId = int.Parse(txtId.Text.Trim());
            myDataSet.Survey_QuestionDataTable surQuesTable = surQuesAdapter.GetDataByQuesId(questionId);
            if (surQuesTable.Rows.Count == 0)
            {
                if (checkEmpty())
                {
                    quesAdapter.UpdateQuery(txtQues.Text.Trim(), int.Parse(DropDownList1.SelectedValue.ToString()), int.Parse(txtId.Text.Trim()));
                    display();
                }
            }
            else
            {
                RegisterStartupScript("as", "<script>alert('Cannot edit this question!')</script>");
            }
        }
    }

    protected void cmdClear_Click(object sender, EventArgs e)
    {
        clear();
        display();
        Panel1.Visible = true;
    }

    protected void cmdHide_Click(object sender, EventArgs e)
    {
        display();
        Panel1.Visible = false;
        cmdSearchEnable.Text = "Enable Search Area";
        cmdAddEnable.Text = "Enable Add Area";
        lblResult.Text = null;
    }

    protected void getDataById(int id)
    {
        myDataSet.QuestionsDataTable quesTable = quesAdapter.GetDataById(id);
        txtId.Text = quesTable[0]["id"].ToString();
        txtQues.Text = quesTable[0]["question"].ToString();
        DropDownList1.SelectedValue = quesTable[0]["question_type_id"].ToString();
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int id = int.Parse(GridView1.DataKeys[e.NewEditIndex].Value.ToString());
        Panel1.Visible = true;
        txtId.Enabled = false;
        txtId.BackColor = System.Drawing.Color.WhiteSmoke;
        cmdSearch.Text = "Save";
        cmdClear.Visible = false;
        cmdSearchEnable.Text = "Enable Search Area";
        cmdAddEnable.Text = "Enable Add Area";
        clear();
        getDataById(id);
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
        myDataSet.Survey_QuestionDataTable surQuesTable = surQuesAdapter.GetDataByQuesId(id);
        if (surQuesTable.Rows.Count == 0)
        {
            answerAdapter.DeleteByQuesIdQuery(id);
            quesAdapter.DeleteQuery(id);
            clear();
            display();
        }
        else
        {
            RegisterStartupScript("as", "<script>alert('Cannot delete this question!')</script>");
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        display();
    }

    protected void cmdAddAnswer_Click(object sender, EventArgs e)
    {
        int questionId = int.Parse(txtQuestionIdAnswer.Text.Trim());
        if (checkAnswerEmpty())
        {
            if (cmdAddAnswer.Text == "Add")
            {
                answerAdapter.InsertQuery(txtAnswer.Text.Trim(), questionId );
                displayAnswer(questionId);
            }
            else
            {
                answerAdapter.UpdateQuery(txtAnswer.Text.Trim(), questionId, int.Parse(txtAnswerId.Text.Trim()));
                displayAnswer(questionId);
                clearAnswer();
                cmdAddAnswer.Text = "Add";
                cmdClearAnswer.Visible = true;
            }
        }
    }

    protected void cmdClearAnswer_Click(object sender, EventArgs e)
    {
        clearAnswer();
        displayAnswer(int.Parse(txtQuestionIdAnswer.Text.Trim()));
    }

    protected void cmdDone_Click(object sender, EventArgs e)
    {
        clearAnswer();
        PanelButton.Visible = true;
        Panel1.Visible = true;
        Panel2.Visible = true;
        Panel3.Visible = false;
        Panel4.Visible = false;
    }

    protected void getDataAnswerById(int id)
    {
        myDataSet.AnswersDataTable answerTable = answerAdapter.GetDataById(id);
        txtAnswerId.Text = answerTable[0]["id"].ToString();
        txtAnswer.Text = answerTable[0]["answer"].ToString();
    }

    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int id = int.Parse(GridView2.DataKeys[e.NewEditIndex].Value.ToString());
        cmdAddAnswer.Text = "Save";
        cmdClearAnswer.Visible = false;
        clearAnswer();
        getDataAnswerById(id);
    }

    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = int.Parse(GridView2.DataKeys[e.RowIndex].Value.ToString());
        answerAdapter.DeleteQuery(id);
        clearAnswer();
        displayAnswer(int.Parse(txtQuestionIdAnswer.Text.Trim()));
    }

    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView2.PageIndex = e.NewPageIndex;
        displayAnswer(int.Parse(txtQuestionIdAnswer.Text.Trim()));
    }
}
